import JsonUtil from '@/js/util/JsonUtil';
import TokenUtil from '@util/TokenUtil';

class HttpUtil {
  /**
   * 远程地址枚举
   * @type {{local_9528: string}}
   */
  originEnum = {
    local_9528: 'http://192.168.31.202:9528',
  };

  /**
   * 远程地址
   * @type {string}
   */
  httpOrigin = this.originEnum.local_9528;

  ContentTypeEnum = {
    contentTypeName: 'Content-Type',
    json: 'application/json;charset=UTF-8',
    form: 'application/x-www-form-urlencoded; charset=UTF-8',
  };
  HttpMethodEnum = {
    GET: 'GET',
    POST: 'POST',
    PUT: 'PUT',
    PATCH: 'PATCH',
    DELETE: 'DELETE',
  };

  /**
   * get 请求
   * @param url
   * @param params
   */
  get = async (url: String, params = {}) => {
    if (!JsonUtil.isJsonObject(params)) {
      throw new Error('请传入json对象格式参数。其他类型参数不会解析');
    }
    if (!JsonUtil.jsonObjectIsEmpty(params)) {
      let _params = Object.keys(params)
        .map(key => `${key}=${params[key]}`)
        .join('&');
      url = `${url}?${_params}`;
    }
    let responsePromise = fetch(`${this.httpOrigin}${url}`, {
      method: this.HttpMethodEnum.GET,
      headers: {
        Authorization: await TokenUtil.getToken(),
        //一般来说 get请求不需要Content-type
        'Content-type': this.ContentTypeEnum.form,
      },
    });
    return this.processResponse(responsePromise);
  };

  /**
   * post 请求
   * @param url
   * @param params
   */
  post = async (url: String, params = {}) => {
    let formData = new FormData();
    Object.keys(params).forEach(key => formData.append(key, params[key]));
    let responsePromise = fetch(`${this.httpOrigin}${url}`, {
      method: this.HttpMethodEnum.POST,
      headers: {
        Authorization: await TokenUtil.getToken(),
        //使用 formData  content-type 默认是 multipart/form-data
        // 'Content-type': this.ContentTypeEnum.form,
      },
      body: formData,
    });
    return this.processResponse(responsePromise);
  };

  /**
   * 检查和处理网络问题
   * @param responsePromise fetch返回对象
   */
  processResponse = async (responsePromise: Promise<Response>) => {
    let response = await responsePromise;
    if (!response.ok) {
      //todo 统一网络异常处理 。换个好点的弹窗
      alert('请求失败' + response.status);
      console.log(`${response.url} 请求失败  `);
      console.log(response);
      return;
    }
    const contentType = response.headers.get('Content-Type');
    if (contentType != null) {
      if (contentType.indexOf('text') > -1) {
        return await response.text();
      }
      if (contentType.indexOf('form') > -1) {
        return await response.formData();
      }
      if (contentType.indexOf('video') > -1) {
        return await response.blob();
      }
      if (contentType.indexOf('json') > -1) {
        return await response.json();
      }
    }
    return await response.text();
  };
}

export default new HttpUtil();
